<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="openSelectMerchandiseDialog">{{$t('添加盘点货品')}}</el-button>
      <el-button type="primary" v-if="submitData.length > 0" @click="deleteCheckMerchandise">{{$t('Delete')}}</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table ref="addMerchandiseTable" :data="submitData" row-key="shopMerchandiseId" border fit highlight-current-row>
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column type="index" width="50"></el-table-column>

      <el-table-column align="center" min-width="50" :label="$t('Merchandise_number')" prop="merchandiseSn"/>

      <el-table-column align="center" min-width="100" :label="$t('Product_name')" prop="name"/>

      <el-table-column align="center" :label="$t('Specifications')" prop="standard"/>

      <el-table-column align="center" :label="$t('Model')" prop="model"/>
      
      <el-table-column align="center" :label="$t('Shop_check_system_stock')" prop="systemSurplusNumber">
        <template slot-scope="scope">
          {{scope.row.systemSurplusNumber + "(" + scope.row.checkUnit + ")"}}
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Shop_check_stock')" prop="checkNumber">
        <template slot-scope="scope">
          <el-input v-model="scope.row.checkNumber" type="number" />
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Notes')" prop="remark">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" :placeholder="$t('Notes_info')" />
        </template>
      </el-table-column>
    </el-table>

    <el-row class="submit-content" v-if="submitData.length > 0">
      <el-col :span="24">
        <el-button type="primary" @click="submitConfirm" align="center">{{$t('Confirm')}}</el-button>
      </el-col>
    </el-row>
    
    <el-dialog :visible.sync="selectMerchandiseDialogVisible" :title="$t('添加盘点货品')" width="60%">
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-input v-model="selectMerchandiseListQuery.merchandiseSn" clearable class="filter-item" style="width: 200px;" :placeholder="$t('Merchandise_number')"/>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSelectMerchandiseFilter">{{$t('Search')}}</el-button>
      </div>

      <!-- 查询结果 -->
      <el-table ref="selectMerchandiseTable" v-loading="selectMerchandiseListLoading" :data="selectMerchandiseList" :element-loading-text="$t('Searching')" 
        row-key="id" border fit highlight-current-row>
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column type="index" :index="getSelectMerchandiseIndex" width="50"></el-table-column>

        <el-table-column align="center" min-width="50" :label="$t('Merchandise_number')" prop="merchandiseSn"/>

        <el-table-column align="center" min-width="100" :label="$t('Product_name')" prop="name"/>

        <el-table-column align="center" :label="$t('Specifications')" prop="standard"/>

        <el-table-column align="center" :label="$t('Model')" prop="model"/>

        <el-table-column align="center" :label="$t('Stock') + '(' + $t('Product_basic_unit') + ')'" prop="basicUnit">
        <template slot-scope="scope">
            {{scope.row.basicNumber + "(" + scope.row.basicUnit + ")"}}
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Stock') + '(' + $t('Product_check_unit') + ')'" prop="number">
        <template slot-scope="scope">
          {{scope.row.number + "(" + scope.row.checkUnit + ")"}}
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('Stock') + '(' + $t('Product_sub_unit') + ')'" prop="number">
        <template slot-scope="scope">
            {{scope.row.number / scope.row.ratio + "(" + scope.row.unit + ")"}}
        </template>
      </el-table-column>

      </el-table>

      <pagination v-show="selectMerchandiseTotal>0" :total="selectMerchandiseTotal" :page.sync="selectMerchandiseListQuery.page" :limit.sync="selectMerchandiseListQuery.limit" @pagination="getSelectMerchandiseList" />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectMerchandiseDialogVisible = false">{{$t('Cancel')}}</el-button>
        <el-button @click="handleSelectMerchandise" type="primary">{{$t('Confirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="submitDialogVisible" :title="$t('Confirm')">
      <div class="app-container">{{$t('保存完之后无法修改，确认保存盘点')}}？</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitDialogVisible = false">{{$t('Cancel')}}</el-button>
        <el-button @click="submit" type="primary">{{$t('Confirm')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { materialShopList } from '@/api/erp'
import {shopCheckAdd} from '@/api/shop'
import { MessageBox } from 'element-ui'

export default {
  name: 'ShopCheckAdd',
  components: { Pagination },
  data() {
    return {
      selectMerchandiseTotal: 0,
      selectMerchandiseListLoading: false,
      selectMerchandiseListQuery: {
        page: 1,
        limit: 20,
        shopId: undefined,
        merchandiseSn: undefined,
        name: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      selectMerchandiseDialogVisible: false,
      selectMerchandiseList: [],
      submitDialogVisible: false,
      submitData: []
    }
  },
  created() {
    if (this.$route.query.shopId) {
      this.selectMerchandiseListQuery.shopId = this.$route.query.shopId
    }
  },
  methods: {
    openSelectMerchandiseDialog () {
      this.selectMerchandiseListQuery.page = 1
      this.selectMerchandiseListQuery.merchandiseSn = ''
      this.selectMerchandiseDialogVisible = true
      this.getSelectMerchandiseList()
    },
    getSelectMerchandiseList() {
      materialShopList(this.selectMerchandiseListQuery).then(res => {
        this.selectMerchandiseList = res.data.data.list
        this.selectMerchandiseTotal = res.data.data.total
      }).catch(() => {
        this.selectMerchandiseList = []
        this.selectMerchandiseListLoading = false
      })
    },
    handleSelectMerchandiseFilter() {
      this.getSelectMerchandiseList()
    },
    handleSelectMerchandise () {
      this.selectMerchandiseDialogVisible = false

      const selectedRow = this.$refs['selectMerchandiseTable'].selection
      selectedRow.forEach(e => {
        let isAdded = false
        this.submitData.forEach(data => {
          if (e.id == data.shopMerchandiseId) {
            isAdded = true;
          }
        })

        if (!isAdded) {
          let merchandise = {
            shopMerchandiseId: e.id,
            merchandiseSn: e.merchandiseSn,
            model: e.model,
            name: e.name,
            unit: e.unit,
            checkUnit: e.checkUnit,
            systemSurplusNumber: e.number,
            checkNumber: 0,
            lossNumber: 0,
            remark: ''
          }

          this.submitData.push(merchandise)
        }
      })
    },
    deleteCheckMerchandise () {
      const selectedRow = this.$refs['addMerchandiseTable'].selection
      if (!selectedRow || selectedRow.length == 0) {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t('请选择数据')
        })
      } else {
        let newSubmitData = []
        this.submitData.forEach(data => {
          let isDeleted = false
          selectedRow.forEach(row => {
            if (row.shopMerchandiseId == data.shopMerchandiseId) {
              isDeleted = true
            }
          })

          if (!isDeleted) {
            newSubmitData.push(data)
          }
        })

        this.submitData = newSubmitData;
      }
    },
    submitConfirm () {
      this.submitDialogVisible = true
    },
    submit () {
      for (var i = 0; i < this.submitData.length; i++) {
        const data = this.submitData[i]
        if (!data.checkNumber && data.checkNumber !== "0" && data.checkNumber !== 0) {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t('请输入货品编码为【' + data.merchandiseSn + '】的盘点库存数量')
          })
          return
        }

        // 计算盘亏库存
        data.lossNumber = data.checkNumber - data.systemSurplusNumber
      }

      const formData = {
        items: this.submitData
      }
      shopCheckAdd(formData).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: '添加成功'
        })
        this.$router.push({ path: '/repository/shopCheck/list' })
      })
      .catch(response => {
        MessageBox.alert(this.$t('Error') + this.$t(response.data.errmsg), this.$t('Warning'), {
          confirmButtonText: this.$t('Confirm'),
          type: 'error'
        })
      })
    },
    getSelectMerchandiseIndex(index) {
      return (index + 1) + (this.selectMerchandiseListQuery.page - 1) * this.selectMerchandiseListQuery.limit;
    }
  }
}
</script>

<style scoped>
.el-row.submit-content {
  text-align: center;
  margin-top: 20px;
}
</style>
